package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyFaceRecordQuery;
import com.zl.tby.icc.*;
import com.zl.tby.model.TbyFaceRecord;
import com.zl.tby.repository.TbyFaceRecordRepo;
import com.zl.tby.service.ITbyFaceRecordService;
import com.zl.tby.vo.TbyFaceRecordForm;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DbContext;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.impl.IPageImpl;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 车辆抓拍记录
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Component
public class TbyFaceRecordServiceImpl implements ITbyFaceRecordService {

    @Db
    private TbyFaceRecordRepo tbyFaceRecordRepo;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<TbyFaceRecord> add(TbyFaceRecord entity) {
        entity.setCreateBy(-1L);
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyFaceRecordRepo.insert(entity, true);
        entity.setId(id);
        return R.ok(entity);
    }

    @Override
    public void addBatch(List<TbyFaceRecord> entityList) {
        tbyFaceRecordRepo.insertList(entityList);
    }

    @Override
    public TbyFaceRecord get(Long id) {
        return tbyFaceRecordRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyFaceRecordForm> page(TbyFaceRecordQuery query) {
        IPage<TbyFaceRecord> iPage = tbyFaceRecordRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getDevId()), "dev_id = ?", query.getDevId())
                    .andIf(StringUtils.isNotEmpty(query.getStartDate()), "grab_time >= ?", query.getStartDate() + " 00:00:00")
                    .andIf(StringUtils.isNotEmpty(query.getEndDate()), "grab_time <= ?", query.getEndDate() + " 23:59:59");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        IccToken token = IccTokenCache.getInstance().getToken();
        String tokenStr = token == null ? "" : token.getAccess_token();
        List<TbyFaceRecordForm> formList = new ArrayList<>();
        iPage.getList().forEach(item -> {
            formList.add(new TbyFaceRecordForm(item, tokenStr));
        });
        return new TbyPageResult(new IPageImpl(formList, iPage.getTotal(), iPage.getSize()), query);
    }

    @Override
    public List<TbyFaceRecordForm> list(TbyFaceRecordQuery query) {
        List<TbyFaceRecord> dataList = tbyFaceRecordRepo.selectList(mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getDevId()), "dev_id = ?", query.getDevId())
                    .andIf(StringUtils.isNotEmpty(query.getStartDate()), "grab_time >= ?", query.getStartDate() + " 00:00:00")
                    .andIf(StringUtils.isNotEmpty(query.getEndDate()), "grab_time <= ?", query.getEndDate() + " 23:59:59");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        IccToken token = IccTokenCache.getInstance().getToken();
        String tokenStr = token == null ? "" : token.getAccess_token();
        List<TbyFaceRecordForm> formList = new ArrayList<>();
        for (TbyFaceRecord entity : dataList) {
            formList.add(new TbyFaceRecordForm(entity, tokenStr));
        }
        return formList;
    }

    @Override
    public void grab() {
        try {
            // 获取当前最近的抓拍时间，用作下一次的开始时间
            List<TbyFaceRecord> dbList = db.table("tby_face_record").orderBy("grab_time desc").limit(1).selectList("grab_time", TbyFaceRecord.class);
            // 开始时间
            Date startDate = null;
            if (dbList != null && dbList.size() > 0) {
                startDate = dbList.get(0).getGrabTime();
                // 向后推迟一秒
                startDate = new Date(startDate.getTime() + 1000);
            } else {
                // 未空，就暂时获取当前日期的0点
                startDate = ToolsUtil.dateString2Util(ToolsUtil.dateUtil2String(new Date(System.currentTimeMillis()), "yyyy-MM-dd") + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            }
            int page = 1;
            int pageNum = 200;
            while(true) {
                R<IccResponse<IccPageVo<IccFaceInfo>>> r = IccUtil.searchFaceRecordList(page, pageNum, ToolsUtil.dateUtil2String(startDate, "yyyy-MM-dd HH:mm:ss"));
                if (r.getData().getCode().compareTo(0) != 0) {
                    break;
                }
                List<IccFaceInfo> list = r.getData().getData().getPageData();
                if (list == null || list.size() == 0) {
                    break;
                }
                List<TbyFaceRecord> entityList = new ArrayList<>();
                for (IccFaceInfo data : list) {
                    entityList.add(IccFaceInfo.convert(data));
                }
                this.tbyFaceRecordRepo.insertList(entityList);
                page++;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
